package com.aacar.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.UndeclaredThrowableException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aacar.dto.Header;
import com.aacar.utils.ErrorCodeConsField;
import com.aacar.utils.Pphconfig;

public class SvrHandlerExceptionResolver implements HandlerExceptionResolver {
	
	Logger logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		
		String errorCode = ErrorCodeConsField.ERROR_MSG_90000;
		String errorMessage =  Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_90000);
		Header mobileHead = JSONObject.parseObject(request.getHeader("mobilehead"),Header.class);
		if(ex instanceof UndeclaredThrowableException) {
			UndeclaredThrowableException undeclaredThrowableException	= (UndeclaredThrowableException)ex;
			Throwable throwable = undeclaredThrowableException.getUndeclaredThrowable();
			if(throwable instanceof TranFailException) {
			    errorCode = ((TranFailException)throwable).getErrorCode();
			    errorMessage = throwable.getMessage();
			}
			//logger.error("Catch Exception: ",throwable);//把漏网的异常信息记入日志
		}else if(ex instanceof TranFailException) {
			errorCode = ((TranFailException)ex).getErrorCode();
			errorMessage = ((TranFailException)ex).getMessage();
			//logger.error("Catch Exception: ",throwable);//把漏网的异常信息记入日志
		}else{
		   logger.error("Catch Exception: ",ex);//把漏网的异常信息记入日志 
		}
        PrintWriter writer;
		try {
			response.setHeader("Content-type", "text/html;charset=UTF-8"); 
			response.setCharacterEncoding("UTF-8"); 
			writer = response.getWriter();
			String service = ",\"serviceCode\": \""+mobileHead.getService()+"\"";
			String retJson = "{\"errorCode\": \""+errorCode+"\",\"errorMessage\": \""+errorMessage+"\""+service+"}";
			logger.info("\n");
			logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
			logger.info("@@@@@@@@ response value: " + JSON.toJSONString(retJson));
			logger.info("@@@@@@@@ response (request url): " + request.getRequestURI());
			logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
	        writer.write(retJson);
	        writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
        return null;
	}

}
